#version 300 es                        
layout(location = 0) in vec4 a_position;
layout(location = 1) in vec3 a_normal;

uniform mat4 u_mvp_matrix;
uniform mat4 u_mv_matrix;
uniform mat4 u_it_mv_matrix;

uniform vec3 u_vector2light; // in eye space, the direction of the directional light
uniform vec4 u_pointlight_pos[3]; // in eye space
uniform vec3 u_pointlight_color[3];

out vec3 color;

vec3 material_color;
vec4 eyespace_pos;
vec3 eyespace_normal;

vec3 get_ambient_lighting()
{
	return material_color * 0.1;
}

vec3 get_directional_lighting() 
{
	return material_color * 0.3 * max(dot(eyespace_normal, u_vector2light), 0.0);
}

vec3 get_point_lighting()
{
	vec3 lightingsum = vec3(0.0);
	for (int i = 0; i < 3; i++) {
		vec3 to_pointlight = vec3(u_pointlight_pos[i]) - vec3(eyespace_pos);
		float distance = length(to_pointlight);
		to_pointlight = normalize(to_pointlight);

		float cosine = max(dot(eyespace_normal, to_pointlight), 0.0);
		lightingsum += (material_color * u_pointlight_color[i] * 5.0 * cosine) / distance;
	}
	return lightingsum;
}

void main()                            
{
	gl_Position = u_mvp_matrix * a_position;
	
	material_color = mix(vec3(0.180, 0.467, 0.153), // dark green
				vec3(0.660, 0.670, 0.680), // stony gray
				a_position.y);

	eyespace_pos = u_mv_matrix * a_position;
	eyespace_normal = normalize(vec3(u_it_mv_matrix * vec4(a_normal, 0.0))); // turn the normal to eye space

	color = get_ambient_lighting();
	color += get_directional_lighting();
	color += get_point_lighting();
}
